/* 
 * Modbus app for RTU.
 * Copyright (c) 2012  apleilx
 * All rights reserved.
 * no limite
 */

/* ----------------------- Platform includes --------------------------------*/
#define _MAPP_MODULE_
#include "mbapp.h"
#include "common.h"
#include "pincfg.h"

#define TEST_MODE MB_RTU_SLAVE

mb_baud_tab_create;

uint8_t mbTestErrCnt = 0;
uint8_t mbTestOkCnt = 0;

typedef struct
{
	uint16_t reg_r[64];
	uint16_t reg_w[64];
} mb_tst_type;

char binitmb = 0;

mb_tst_type mb_tst;

void rcv_end_handle_comp(uint8_t ErrSt);
void mb_app_init(void);

/******************************************************************************
* @brief   	Slave device handle.
*               
* @param   none
*
* @return  none
*
* @ Pass/ Fail criteria: none
*****************************************************************************/
void modbus_task(void)
{
	if (!binitmb)
	{
		binitmb = 1;
		mb_app_init();
	}

	if (mb.obj01.rcv_st == MB_RX_RCVEND)
	{
		NOP1();
	}

	mb_poll(&mb.obj01);
}

void mb_app_init(void)
{
	mb_cmd_buff_type mcmd;

	mb_obj_init(&mb.obj01);

	//master config
	mb01_Init(MB_RTU_MASTER, MB_BAUD_115200, MB_PAR_NONE);
	mb.obj01.slave_id = 1;
	mb.obj01.rtu_master_delay_set = 3;
	mb.obj01.rcv_end_handle_comp = rcv_end_handle_comp;
	mb.obj01.os_event_send = 0;
	mb.obj01.os_event_base = 2 << 4;
	mb.obj01.rtu_length_cut = 1;

	//cmd config
	mcmd.device_id = 0;
	mcmd.cmd = FUN_CODE_READ_COILS;
	mcmd.dat = mb_tst.reg_r;
	mcmd.dat_addr = 0;
	mcmd.amount = 48;
	mcmd.call_back = 0;
	mmb_stc_cmd_req(&mb.obj01, 0, &mcmd);

	mcmd.cmd = FUN_CODE_READ_DISCRETE;
	mmb_stc_cmd_req(&mb.obj01, 1, &mcmd);

	mcmd.cmd = FUN_CODE_W_R_MULTIPLE_REG;
	mmb_stc_cmd_req(&mb.obj01, 2, &mcmd);

	mcmd.cmd = FUN_CODE_W_R_MULTIPLE_REG;
	mmb_stc_cmd_req(&mb.obj01, 3, &mcmd);

	mcmd.cmd = FUN_CODE_WRITE_MULTIPLE_REG;
	mmb_stc_cmd_req(&mb.obj01, 4, &mcmd);

}

void rcv_end_handle_comp(uint8_t ErrSt)
{
}
